package time_task

import (
	"fmt"
	"time"

	. "chess_platform/internal/common"
	"github.com/astaxie/beego/orm"
)

func RecordTime(multiOrm ...orm.Ormer) (result map[int64]int64) {
	sql := fmt.Sprintf(`
		SELECT
			type,record_day
		FROM
			%v
	`, TableRecordDay)
	type RecordDay struct {
		Type      int64 `json:"type"`
		RecordDay int64 `json:"record_day"`
	}
	var recordDay []RecordDay
	o := NewOrm(multiOrm, DBChessLog)
	o.Raw(sql).QueryRows(&recordDay)
	result = make(map[int64]int64, 6)
	for _, v := range recordDay {
		result[v.Type] = v.RecordDay
	}
	return
}

func NewOrUpdateRecordDay(typ, recordDay, costTime int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	data := map[string]interface{}{
		"record_day": recordDay,
		"type":       typ,
		"cost_time":  costTime,
	}
	values, sql := InsertOrUpdateSql(TableRecordDay, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func ForExecute(f func(int64) error, typ, recordDay int64) error {
	LogPc.Debug(fmt.Sprintf("typ:%v,recordDay:%v", typ, recordDay))
	t := time.Now().Unix()
	if recordDay == 0 { //如果是刚开始没有记录,所以必然为0
		NewOrUpdateRecordDay(typ, t, 0)
		return nil
	}
	for recordDay < t && !IsSameDay(recordDay, t) {
		start := time.Now().Unix()
		err := f(recordDay)
		if err != nil {
			return err
		}
		end := time.Now().Unix()
		recordDay = recordDay + 86400 //24 * 3600
		NewOrUpdateRecordDay(typ, recordDay, end-start)
		time.Sleep(TimeSleep * time.Second) //睡眠15秒,防止集中执行,cpu,mysql占用率过高
	}
	return nil
}

const (
	TimeSleep = 15 //每执行一个统计睡眠15秒,防止cpu,mysql占用率过高

	RecordDayAllAgent      = 1
	RecordDayLevel1Agent   = 2
	RecordDayGroup         = 3
	RecordMonthAgent       = 4
	RecordMonthLevel1Agent = 5
	RecordMonthGroup       = 6
	RecordDayTrans         = 7
	RecordDayClub          = 8
	RecordDaySystemUser    = 9
	RecordDayChess         = 10
)

func Stat() error {
	LogPc.Info("-----------------进入统计函数----------------------------")
	r := RecordTime()
	StatDayClub(r)
	StatSystemUser(r)
	StatDayChess(r)
	StatAgent(r)
	StatDayTrans(r)
	LogPc.Info("-----------------退出统计函数----------------------------")
	return nil
}
